import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";

function LoginButton(props) {
  return <button onClick={props.handleClick}>Login</button>;
}

function LogoutButton(props) {
  return <button onClick={props.handleClick}>Logout</button>;
}

// 必须在原生的HTML标签上绑定事件才是有效的
class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = { isLoggedIn: false };
  }

  handleLoginClick() {
    this.setState({ isLoggedIn: true });
  }

  handleLogoutClick() {
    this.setState({ isLoggedIn: false });
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) {
      button = <LogoutButton handleClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton handleClick={this.handleLoginClick} />;
    }

    return <div>{button}</div>;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<LoginControl />);
